<template>
  <section class="todoapp">
    <TodoHeader @addTask='hAddTask'/>
    <TodoMain :list="showList" @changeAll="hChangeAll" @delTask="delTask" @changeDone="hChangeDone"/>
    <TodoFooter :list="showList" @clearDone="hClearDone" @changeType="hChangeType"/>
  </section>
</template>

<script>
import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'
export default {
  // 局部注册组件
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter
  },
  data () {
    return {
      // list: [
      //   { id: 1, name: '吃饭', isDone: true },
      //   { id: 2, name: '睡觉', isDone: false },
      //   { id: 3, name: '打豆豆', isDone: true }
      // ],
      list:JSON.parse(localStorage.getItem('list') || '[]'),
      type:'all'
    }
  },
  methods: {
    // 删除数据
    delTask(id) {
      const index = this.list.findIndex(item => item.id === id)
      this.list.splice(index ,1)
    },
    hChangeDone(id){
      const obj = this.list.find(item => item.id === id)
      obj.isDone = !obj.isDone
    },
    hAddTask(taskname){
      this.list.push({
        name:taskname,
        id:Date.now,
        isDone:false
      })
    },
    hClearDone(){
      this.list = this.list.filter(item => !item.isDone)
    },
    hChangeType(type){
      this.type = type
    },
    hChangeAll(val){
      this.list.forEach(element => item.isDone = val)
    }
  },
  computed:{
    showList(){
      if(this.type === 'all'){
        return this.list
      }else if(this.type === 'active'){
        return this.list.filter(item => !item.isDone)
      }else if(this.list.filter(item => !item.isDone)){
        return this.list.filter(item => item.isDone)
      }
    }
  },
  watch:{
    list:{
      deep:true,
      handler(){
        localStorage.setItem('list',JSON.stringify(this.list))
      }
    }
  }
}
</script>

<style>

</style>
